package br.com.foxline.atlasmobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import br.com.foxline.atlasmobile.dao.AnnexDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Annex;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.util.UtilConnection;

public class ConfigPortActivity extends Activity {

	private SharedPreferences prefs;
	private EditText serverEdit;
	private EditText portNumberEdit;
	private EditText qtdImoveisSincronizados;
	private CheckBox checkExport;
//	private Button buttonSync;
	//btn_reinit
	private Button buttonReinit;

	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View arg) {
			export(arg.getContext());
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_config_port);

		serverEdit = ((EditText) findViewById(R.id.serverEdit));
		portNumberEdit = ((EditText) findViewById(R.id.portNumberEdit));
		checkExport = ((CheckBox) findViewById(R.id.check_export));

		Button buttonSync = (Button) findViewById(R.id.btn_sync_dne);
		buttonSync.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				reenviarTodas();
			}
		});

		Button processCodImagem = (Button) findViewById(R.id.processcod);
		processCodImagem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				processCodImage();
			}
		});

		Button exportarBd = (Button) findViewById(R.id.exportarbd);
		exportarBd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				exportDB();
			}
		});
		qtdImoveisSincronizados = ((EditText) findViewById(R.id.edit_qtd_imovel_sincronizado));

//		buttonSync.setOnClickListener(listener);
		prefs = getSharedPreferences(UtilConnection.APP_SHARED_PREFS, 0);
		catchServer();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_config_port, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		}
		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		salvar(null);
	}

	public void salvar(View view) {
		Toast.makeText(getApplicationContext(), "Configurações Salvas !",
				Toast.LENGTH_SHORT).show();
		String server = serverEdit.getEditableText().toString();
		String portNumber = portNumberEdit.getEditableText().toString();
		Boolean check = checkExport.isChecked();
		int qtdImoveis = Integer.parseInt(qtdImoveisSincronizados
				.getEditableText().toString());

		Editor editor = prefs.edit();
		editor.putBoolean(UtilConnection.CHECK, check);
		editor.putString(UtilConnection.SERVER, server);
		editor.putString(UtilConnection.PORT_NUMBER, portNumber);
		editor.putInt(UtilConnection.QTD_IMOVEIS_SINCRONIZADOS_SIMULTANEAMENTE,
				qtdImoveis);
		editor.commit();
		finish();
	}

	public void catchServer() {
		checkExport.setChecked(prefs.getBoolean(UtilConnection.CHECK, true));

		serverEdit.setText(prefs.getString(UtilConnection.SERVER,
				UtilConnection.SERVER_DEFAULT));
		portNumberEdit.setText(prefs.getString(UtilConnection.PORT_NUMBER,
				UtilConnection.PORT_NUMBER_DEFAULT));
		try {
			qtdImoveisSincronizados
					.setText(""
							+ prefs.getInt(
									UtilConnection.QTD_IMOVEIS_SINCRONIZADOS_SIMULTANEAMENTE,
									UtilConnection.QTD_IMOVEIS_SINCRONIZADOS_SIMULTANEAMENTE_DEFAULT));
		} catch (Exception e) {
			qtdImoveisSincronizados.setText(10);
		}
	}

	private void export(Context context) {
		// ImportDne importDne = new ImportDne(context);
		// importDne.execute();
	}

	private void reenviarTodas() {
		
		
	}
	private void processCodImage() {
		ProcessaCodImagens codImagens = new ProcessaCodImagens(this);
		codImagens.execute();
	}

	private void exportDB() {
		Backup backup = new Backup(this);
		backup.execute();
	}

	class Backup extends AsyncTask<Void, String, String> {

		private ProgressDialog dialog;
		
		public Backup(Context context) {
			this.dialog = new ProgressDialog(context);
			this.dialog.setTitle("Backup");
			this.dialog.setMessage("Processando...");
			this.dialog.setCancelable(false);

			this.dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Fechar",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			this.dialog.show();
		}
		@Override
		protected String doInBackground(Void... params) {
			try {
				File sd = Environment.getExternalStorageDirectory();
				File data = Environment.getDataDirectory();

				if (sd.canWrite()) {
					String currentDBPath = "//data//"
							+ "br.com.foxline.atlasmobile" + "//databases//"
							+ "atlasmobile.db";
					SimpleDateFormat format = new SimpleDateFormat(
							"dd-MM-yyyy-mm-ss");
					String backupDBPath = "/atlasmobile_backup_" + format.format(new Date())+".db";

					System.err.println(backupDBPath);
					File currentDB = new File(data, currentDBPath);
					File backupDB = new File(sd, backupDBPath);

					FileChannel src = new FileInputStream(currentDB).getChannel();
					FileChannel dst = new FileOutputStream(backupDB).getChannel();
					dst.transferFrom(src, 0, src.size());
					src.close();
					dst.close();
					publishProgress("Backup com sucesso!");
				}
			} catch (Exception e) {
				e.printStackTrace();
				publishProgress("Backup Falhou");
			}
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			if (values.length > 0 && values[0] != null) {
				dialog.setMessage(values[0] + "");
			}

		}
		
	}
	
	class ProcessaCodImagens extends AsyncTask<Void, String, String> {

		private ProgressDialog dialog;
		private ImovelDao imovelDao;
		private AnnexDao annexDao;
		private Context context;

		public ProcessaCodImagens(Context context) {
			this.context = context;
			this.imovelDao = new ImovelDao(context);
			this.annexDao = new AnnexDao(context);

			this.dialog = new ProgressDialog(context);
			this.dialog.setTitle("Enviando");
			this.dialog.setMessage("Conectando...");
			this.dialog.setCancelable(false);

			this.dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Fechar",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							closeDialog();
						}
					});

			this.dialog.show();

		}

		@Override
		protected String doInBackground(Void... params) {
			List<Imovel> list = imovelDao.getAllFromList(annexDao
					.exportOnlyAnnexNotSending());

			for (Long imovel : annexDao.exportOnlyAnnexNotSending()) {
				Imovel enviado = imovelDao.getEnviado(imovel);
				if (enviado != null && enviado.getAnnex() != null) {

					for (Annex a : enviado.getAnnex()) {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"dd-MM-yyyy-HH-mm-ss");
						a.setCod("#" + a.getId() + "#" + a.getUUID() + "#"
								+ sdf.format(a.getCreate_at()));

						publishProgress("Enviando Anexo: " + a.getId());

						annexDao.update(a);
					}
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dialog.setMessage("Concluído ! \n");
		}

		private void closeDialog() {
			dialog.dismiss();
			cancel(true);
		}
	}

}
